import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import qs from 'qs';

const baseURL = import.meta.env.VITE_API_BASE_URL;

// 定义基础响应类型
export interface BaseResponse<T = any> {
  code: number;
  message: string;
  result: T;
  success: boolean;
  timestamp: number;
}

class Http {
  static instance: Http | null = null;
  private axiosInstance: AxiosInstance;

  constructor(baseURL: string, timeout = 5000) {
    this.axiosInstance = axios.create({
      baseURL,
      timeout,
      paramsSerializer: (params: Record<string, any>) => qs.stringify(params), // 使用 qs 序列化参数
    });

    this.axiosInstance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // if (config.params) {
        //   config.params = qs.stringify(config.params); // 确保参数序列化
        // }
        return config;
      },
      (error) => {
        console.error('Request Interceptor Error:', error);
        return Promise.reject(error);
      }
    );


    this.axiosInstance.interceptors.response.use(
      (response: AxiosResponse<BaseResponse>) => {
        const { code, message, result, success, timestamp } = response.data;
        if (code !== 200) {
          console.error('Response Error:', message);
          throw new Error(message); // 抛出错误以便统一处理
        }
        return response;
      },
      (error) => {
        console.error('Response Interceptor Error:', error);
        return Promise.reject(error);
      }
    );
  }
  static getInstance(baseURL: string, timeout?: number): Http {
    if (!Http.instance) {
      Http.instance = new Http(baseURL, timeout);
    }
    return Http.instance;
  }

  get<T = any>(url: string, params?: Record<string, any>): Promise<BaseResponse<T>> {
    console.log('get', url, params);
    return this.axiosInstance.get(url, { params }).then((res) => {
      return res.data;
    });
  }

  post<T = any>(url: string, data?: Record<string, any>): Promise<BaseResponse<T>> {
    return this.axiosInstance.post(url, data).then((res) => {
      return res.data;
    });
  }

  put<T = any>(url: string, data?: Record<string, any>): Promise<BaseResponse<T>> {
    return this.axiosInstance.put(url, data).then((res) => {
      return res.data;
    });
  }

  delete<T = any>(url: string, params?: Record<string, any>): Promise<BaseResponse<T>> {
    return this.axiosInstance.delete(url, { params }).then((res) => {
      return res.data;
    });
  }
}

export const defHttp = Http.getInstance(baseURL);

export default Http;